<template>
  <div class="qa-wrapper">
    <div class="wrapper-header">
      <div class="switch">
        <!-- 筛选项 -->
        <el-select style="width: 170px" v-model="selectedStatus" placeholder="筛选申请状态" @change="fetchRecords">
          <el-option v-for="status in statusOptions" :key="status.value" :label="status.label" :value="status.value" />
        </el-select>
        <span style="margin-left: 5px"><el-input v-model="findUserName" placeholder="输入姓名搜索"></el-input></span>
        <span style="margin-left: 5px"><el-input v-model="findUserMobile" placeholder="输入手机搜索"></el-input></span>
      </div>
      <div class="search">
        <el-button @click="fetchRecords" type="primary">查询</el-button>
      </div>
    </div>
    <el-table v-loading="loading" :data="currentApplyRecords" style="width: 100%" :row-class-name="tableRowClassName">
      <el-table-column type="expand">
        <template #default="props">
          <el-descriptions style="margin-left: 10px" title="提交信息" :column="3" border>
            <el-descriptions-item label="微信号：">{{ props.row.wechat || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="手机号：">{{ props.row.phone || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="身份证号：">{{ props.row.idCard || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="卡号：">{{ props.row.bankNum || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="户籍地址：">{{ props.row.domicile || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="现居住地址：">{{ props.row.address || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="公司：">{{ props.row.org || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="公司地址：">{{ props.row.orgAddress || '暂无信息' }}</el-descriptions-item>
            <el-descriptions-item label="单位电话：">{{ props.row.orgTel || '暂无信息' }}</el-descriptions-item>
          </el-descriptions>
          <el-descriptions style="margin-left: 10px; margin-top: 5px" :column="2" border>
            <el-descriptions-item label="紧急联系人1：" width="130px">{{
              props.row.contact1 || '暂无信息'
            }}<el-tag v-if="props.row.contact1Id">{{ props.row.contact1Id }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="紧急联系人1电话：" width="200px">{{
              props.row.contactTel1 || '暂无信息'
            }}</el-descriptions-item>
            <el-descriptions-item label="紧急联系人2：" width="130px">{{
              props.row.contact2 || '暂无信息'
            }}<el-tag v-if="props.row.contact1Id">{{ props.row.contact2Id }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="紧急联系人2电话：" width="200px">{{
              props.row.contactTel2 || '暂无信息'
            }}</el-descriptions-item>
             <el-descriptions-item label="紧急联系人3：" width="130px">{{
              props.row.contact3 || '暂无信息'
            }}<el-tag v-if="props.row.contact3Id">{{ props.row.contact3Id }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="紧急联系人3电话：" width="200px">{{
              props.row.contactTel3 || '暂无信息'
            }}</el-descriptions-item>
          </el-descriptions>
          <el-descriptions style="margin-left: 10px; margin-top: 5px" :column="2" border>
            <el-descriptions-item label="支付宝芝麻分截图：">
              <el-image
                v-if="getPreviewUrl(props.row.zfbUrl)"
                ref="imageRef"
                style="width: 50px; height: 50px"
                :src="getPreviewUrl(props.row.zfbUrl)"
                :preview-src-list="[getPreviewUrl(props.row.zfbUrl)]"
                fit="cover"
              />
              <el-button
                size="small"
                type="primary"
                v-else-if="props.row.zfbUrl"
                @click.prevent.stop="openImage('zfb', props.row.zfbUrl)"
                >加载截图</el-button
              >
              <span v-else>暂无信息</span>
            </el-descriptions-item>
            <el-descriptions-item label="公积金首页明细：">
              <el-image
                v-if="getPreviewUrl(props.row.gjjUrl)"
                ref="imageRef"
                style="width: 50px; height: 50px"
                :src="getPreviewUrl(props.row.gjjUrl)"
                :preview-src-list="[getPreviewUrl(props.row.gjjUrl)]"
                fit="cover"
              />
              <el-button
                size="small"
                type="primary"
                v-else-if="props.row.gjjUrl"
                @click.prevent.stop="openImage('gjj', props.row.gjjUrl)"
                >查看图片</el-button
              >
              <span v-else>暂无信息</span>
            </el-descriptions-item>
            <el-descriptions-item label="身份证正面：">
              <el-image
                v-if="getPreviewUrl(props.row.idFrontUrl)"
                ref="imageRef"
                style="width: 50px; height: 50px"
                :src="getPreviewUrl(props.row.idFrontUrl)"
                :preview-src-list="[getPreviewUrl(props.row.idFrontUrl)]"
                fit="cover"
              />
              <el-button
                size="small"
                type="primary"
                v-else-if="props.row.idFrontUrl"
                @click.prevent.stop="openImage('idFront', props.row.idFrontUrl)"
                >查看图片</el-button
              >
              <span v-else>暂无信息</span>
            </el-descriptions-item>
            <el-descriptions-item label="身份证反面：">
              <el-image
                v-if="getPreviewUrl(props.row.idBackUrl)"
                ref="imageRef"
                style="width: 50px; height: 50px"
                :src="getPreviewUrl(props.row.idBackUrl)"
                :preview-src-list="[getPreviewUrl(props.row.idBackUrl)]"
                fit="cover"
              />
              <el-button
                size="small"
                type="primary"
                v-else-if="props.row.idBackUrl"
                @click.prevent.stop="openImage('idBack', props.row.idBackUrl)"
                >查看图片</el-button
              >
              <span v-else>暂无信息</span>
            </el-descriptions-item>
            <el-descriptions-item label="手持身份证照片：">
              <el-image
                v-if="getPreviewUrl(props.row.idPhotoUrl)"
                ref="imageRef"
                style="width: 50px; height: 50px"
                :src="getPreviewUrl(props.row.idPhotoUrl)"
                :preview-src-list="[getPreviewUrl(props.row.idPhotoUrl)]"
                fit="cover"
              />
              <el-button
                size="small"
                type="primary"
                v-else-if="props.row.idPhotoUrl"
                @click.prevent.stop="openImage('idPhoto', props.row.idPhotoUrl)"
                >查看图片</el-button
              >
              <span v-else>暂无信息</span>
            </el-descriptions-item>
            <el-descriptions-item label="备注：">
              <el-tag size="small">{{ props.row.remark || '暂无备注' }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <el-table-column label="产品">
        <template #default="props">
          <span style="font-size: 17px; color: goldenrod; font-weight: bold">{{ props.row.limitAmount }}</span>
          <div>
            <el-tag size="small" style="font-weight: 200; color: black">{{ props.row.weekNum }}期</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name"> </el-table-column>
      <el-table-column label="手机号码" prop="phone"> </el-table-column>
      <el-table-column label="状态">
        <template #default="props">
          <el-tag :type="getStatusTag(props.row.status)">{{ getStatusLabel(props.row.status) }}</el-tag>
          <template v-if="props.row.status === 'APPROVED' && !props.row.userCommit">
            <el-tag type="info">等待用户确认</el-tag>
          </template>
          <template v-if="props.row.status === 'APPROVED' && props.row.userCommit">
            <el-tag type="scucess">已确认，等待放款</el-tag>
            <br />
            <span style="font-size: 11px" v-if="props.row.userCommitDate"
              >用户确认时间： {{ formatISOTimeByValue(props.row.userCommitDate) }}</span
            >
          </template>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" prop="createdAt" :formatter="formatISOTime"> </el-table-column>
      <!-- 其他列 -->
      <el-table-column label="操作">
        <template #default="scope">
          <el-dropdown @command="handleDropdownCommand(scope.row, $event)">
            <el-button type="primary">
              操作
              <template #icon>
                <ArrowDown />
              </template>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="modifyStatus">修改状态</el-dropdown-item>
                <el-dropdown-item command="modifyWeekNum">修改期数</el-dropdown-item>
                <el-dropdown-item command="modifyProduct">修改产品</el-dropdown-item>
                <!-- <el-dropdown-item command="modifyBasicInfo">修改基础信息</el-dropdown-item> -->
                <el-dropdown-item command="addRemark">添加备注</el-dropdown-item>
                <el-dropdown-item command="deleted">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-left: 10px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="sizes, prev, pager, next, jumper, total"
      :total="total"
    >
    </el-pagination>
    <!-- 修改状态弹窗 -->
    <el-dialog v-model="statusDialogVisible" title="修改状态">
      <el-form :model="selectedRecord" v-if="selectedRecord">
        <el-form-item label="当前状态：">
          <span>{{ getStatusLabel(selectedRecord.status) }}</span>
        </el-form-item>
        <el-form-item label="新状态：">
          <el-select v-model="newStatus" placeholder="请选择状态">
            <el-option
              v-for="status in statusOptions.filter((s:any) => s.value)"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmModifyStatus">提交</el-button>
      </template>
    </el-dialog>
    <!-- 修改产品弹窗 -->
    <el-dialog v-model="productDialogVisible" title="修改产品">
        <el-form :model="selectedRecord" v-if="selectedRecord">
          <el-form-item label="当前产品：">
            <span v-if="selectedRecord.limitAmount === 10000" >鼠茶宝10000</span>
            <span v-else>鼠茶宝15000</span>
          </el-form-item>
          <el-form-item label="新产品：">
            <el-select v-model="newProduct" placeholder="请选择产品">
              <el-option label="鼠茶宝15000" value="15000"></el-option>
              <el-option label="鼠茶宝10000" value="10000"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="productDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmModifyProduct">提交</el-button>
        </template>
      </el-dialog>

    <!-- 修改期数弹窗 -->
    <el-dialog v-model="weekNumDialogVisible" title="修改期数">
      <el-form :model="selectedRecord" v-if="selectedRecord">
        <el-form-item label="当前期数：">
          <span>{{ selectedRecord.weekNum }}期</span>
        </el-form-item>
        <el-form-item label="新期数：">
          <el-select v-model="newWeekNum" placeholder="请选择期数">
            <el-option label="4期" value="4"></el-option>
            <el-option label="8期" value="8"></el-option>
            <el-option label="12期" value="12"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="weekNumDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmModifyWeekNum">提交</el-button>
      </template>
    </el-dialog>

    <!-- 修改基础信息弹窗 -->
    <el-dialog v-model="basicInfoDialogVisible" title="修改基础信息">
      <el-form :model="selectedRecord" v-if="selectedRecord" label-position="right">
        <el-form-item label="姓　名">
          <el-input v-model="selectedRecord.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="selectedRecord.phone"></el-input>
        </el-form-item>
        <el-form-item label="微信号">
          <el-input v-model="selectedRecord.wechat"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="basicInfoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmModifyBasicInfo">提交</el-button>
      </template>
    </el-dialog>

    <!-- 添加备注弹窗 -->
    <el-dialog v-model="remarkDialogVisible" title="添加备注">
      <el-form :model="selectedRecord">
        <el-form-item label="备注">
          <el-input v-model="newRemark" type="textarea" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="remarkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddRemark">提交</el-button>
      </template>
    </el-dialog>
    <AdminKeyDialog ref="adminKeyDialog"></AdminKeyDialog>
  </div>
</template>
<style scoped>
@import '../style/applyReview.less';
</style>
<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as httpService from '@/services/apply.service'
import { useUserStore } from '@/stores/useStore'
import { ApplyModule } from '@/services/modules/apply'
import { formatISOTime, formatISOTimeByValue } from '@/utils/helper'
import AdminKeyDialog from './AdminKeyDialog.vue'

const applyRecords = ref<ApplyModule.ApplyRecord[]>([])
const currentApplyRecords = ref<ApplyModule.ApplyRecord[]>([])
const selectedStatus = ref('')
const findUserName = ref('')
const findUserMobile = ref('')
const adminKeyDialog = ref<InstanceType<typeof AdminKeyDialog>>()

// 打开管理员密钥对话框并获取密钥
const openAdminKeyDialog = () => {
  if (!useUserStore().authInfo?.opCode) {
    adminKeyDialog.value?.show();
    return false;
  } else {
    return true;
  }
}

const tableRowClassName = computed(() => {
  return 'success-row'
})
// 状态选项
const statusOptions = [
  { label: '全部', value: '', color: '#999' },
  { label: '已提交，等待审核', value: 'SUBMITTED', color: '#0084ff' },
  { label: '审核中', value: 'UNDER_REVIEW', color: '#ff9900' },
  { label: '审核通过', value: 'APPROVED', color: '#00cc00' },
  { label: '已放款', value: 'DISBURSED', color: '#ff0000' },
  { label: '已还款', value: 'REPAID', color: '#00cc00' },
  { label: '已关闭', value: 'CLOSED', color: '#999' },
]
// 当前选中要修改状态的记录
const selectedRecord = ref<ApplyModule.ApplyRecord | null>(null)

// 控制状态修改弹窗的显示与隐藏
// 控制各个弹窗的显示与隐藏
const statusDialogVisible = ref(false)
const productDialogVisible = ref(false)
const weekNumDialogVisible = ref(false)
const basicInfoDialogVisible = ref(false)
const remarkDialogVisible = ref(false)


// 新选择的状态
const newStatus = ref('')
// 新选择的期数
const newWeekNum = ref<number | null>(null)
// 新添加的备注
const newRemark = ref('')
const newProduct = ref<number | null>(null)
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(true)

// 存储预览链接的 Map
const previewUrlMap = ref(new Map<string, string>())

const getPreviewUrl = (fileUrl: string | undefined) => {
  if (fileUrl) {
    return previewUrlMap.value.get(fileUrl)
  }
  return undefined
}

const openImage = async (imageType: string, fileUrl: string) => {
  try {
    const response = await httpService.getDownloadUrl({ fileId: fileUrl })
    if (response.data.errcode === 0 && response.data.file_list.length > 0) {
      const downloadUrl = response.data.file_list[0].download_url
      previewUrlMap.value.set(fileUrl, downloadUrl)
    } else {
      console.error('获取下载链接失败:', response.data.errmsg)
    }
  } catch (error) {
    console.error('请求下载链接时出错:', error)
  }
}

// 处理下拉菜单命令
const handleDropdownCommand = async (row: ApplyModule.ApplyRecord, command: string) => {
  const hasOpCode = openAdminKeyDialog();
  if (!hasOpCode) {
     return;
  }
  selectedRecord.value = row
  switch (command) {
    case 'modifyStatus':
      newStatus.value = row.status
      statusDialogVisible.value = true
      break
    case 'modifyWeekNum':
      newWeekNum.value = row.weekNum
      weekNumDialogVisible.value = true
      break
    case 'modifyBasicInfo':
      basicInfoDialogVisible.value = true
      break
    case 'modifyProduct':
      productDialogVisible.value = true
      break
    case 'addRemark':
      newRemark.value = row.remark || ''
      remarkDialogVisible.value = true
      break
    case 'deleted':
      ElMessageBox.confirm('确认要删除该申请记录吗？', '提示', {
        type: 'warning',
      })
        .then(async () => {
          try {
            if (row.id) {
              const opCode = useUserStore().authInfo?.opCode || '';
              await httpService.deleteApplyRecord(row.id, opCode)
              ElMessage.success('删除成功')
              // 从 applyRecords 中移除该条记录
              applyRecords.value = applyRecords.value.filter(item => item.id!== row.id)
              // 从 currentApplyRecords 中移除该条记录
              currentApplyRecords.value = currentApplyRecords.value.filter(item => item.id!== row.id)
              // 更新总记录数
              total.value--
            }
          } catch (error) {
            ElMessage.error('删除失败，请稍后重试')
          }
        })
        .catch(() => {
          ElMessage.info('操作已取消')
        })
      break
    default:
      break
  }
}

// 获取状态文本
const getStatusLabel = (cellValue: string) => {
  const option = statusOptions.find((s) => s.value === cellValue)
  return option ? option.label : '未知'
}

// 获取状态颜色
const getStatusTag = (status: string) => {
  const statusMap = {
    SUBMITTED: 'info',
    UNDER_REVIEW: 'warning',
    APPROVED: 'success',
    DISBURSED: 'primary',
    REPAID: 'success',
    CLOSED: 'danger',
  } as any
  return statusMap[status] || 'info'
}

// 打开状态修改弹窗
const openStatusDialog = (record: ApplyModule.ApplyRecord) => {
  selectedRecord.value = record
  newStatus.value = record.status
  statusDialogVisible.value = true
}

// 确认修改状态
const confirmModifyStatus = async () => {
  if (!selectedRecord.value || !selectedRecord.value.id) return
  if (newStatus.value === selectedRecord.value.status) {
    ElMessage.info('状态未改变，无需修改')
    statusDialogVisible.value = false
    return
  }
  if (!newStatus.value) {
    return ElMessage.error('状态不能为空')
  }

  try {
    let prompt = ''
    if (newStatus.value === 'DISBURSED') {
      prompt = '修改为放款状态后不可再修改，且会为该用户生成还款日历，请谨慎操作'
    }
    if (newStatus.value === 'CLOSED') {
      prompt = '修改为【已关闭】状态，将会把此申请所有的【任务】的状态也同步设置为“已关闭”，请谨慎操作'
    }
    // 二次确认
    await ElMessageBox.confirm(
      `确定将状态从 【${getStatusLabel(selectedRecord.value.status)}】 修改为 【${getStatusLabel(
        newStatus.value
      )}】 吗？${prompt}`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    const hasOpCode = openAdminKeyDialog();
    if (!hasOpCode) {
      return;
    }
    const opCode = useUserStore().authInfo?.opCode || '';
    // 这里调用实际的修改状态的 API
    await httpService.modifyApplyRecordStatus({ recordId: selectedRecord.value.id, status: newStatus.value, opCode: opCode })
    // 假设修改成功后更新表格数据
    selectedRecord.value.status = newStatus.value as any
    ElMessage.success('状态修改成功')
    statusDialogVisible.value = false
  } catch (error) {
    // 用户取消操作
    ElMessage.info('操作已取消')
  }
}

// 确认修改期数
const confirmModifyWeekNum = async () => {
  if (!selectedRecord.value || !selectedRecord.value.id) return
  if (newWeekNum.value === selectedRecord.value.weekNum) {
    ElMessage.info('期数未改变，无需修改')
    weekNumDialogVisible.value = false
    return
  }
  if (!newWeekNum.value) {
    return ElMessage.error('期数不能为空')
  }

  try {
    await ElMessageBox.confirm(
      `确定将期数从 【${selectedRecord.value.weekNum} 期】修改为 【${newWeekNum.value} 期】吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    const hasOpCode = openAdminKeyDialog();
    if (!hasOpCode) {
      return;
    }
    const opCode = useUserStore().authInfo?.opCode || '';
    // 调用修改期数的服务
    // 假设这里有对应的服务方法
    await httpService.modifyApplyRecordWeekNum({
      recordId: selectedRecord.value.id,
      weekNum: newWeekNum.value,
      opCode: opCode
    })

    selectedRecord.value.weekNum = newWeekNum.value
    ElMessage.success('期数修改成功')
    weekNumDialogVisible.value = false
  } catch (error) {
    ElMessage.info('操作已取消')
  }
}

// 确认修改期数
const confirmModifyProduct = async () => {
  if (!selectedRecord.value || !selectedRecord.value.id) return
  if (newProduct.value === selectedRecord.value.limitAmount) {
    ElMessage.info('产品未改变，无需修改')
    weekNumDialogVisible.value = false
    return
  }
  if (!newProduct.value) {
    return ElMessage.error('产品不能为空')
  }

  try {
    await ElMessageBox.confirm(
      `确定将产品从 【鼠茶宝${selectedRecord.value.limitAmount} 】修改为 【鼠茶宝${newProduct.value} 】吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    const hasOpCode = openAdminKeyDialog();
    if (!hasOpCode) {
      return;
    }
    const opCode = useUserStore().authInfo?.opCode || '';
    // 调用修改期数的服务
    // 假设这里有对应的服务方法
    await httpService.modifyApplyRecordProduct({
      recordId: selectedRecord.value.id,
      limitAmount: newProduct.value,
      opCode: opCode
    })

    selectedRecord.value.limitAmount = newProduct.value
    ElMessage.success('产品修改成功')
    productDialogVisible.value = false
  } catch (error) {
    ElMessage.info('操作已取消')
  }
}

// 确认修改基础信息
const confirmModifyBasicInfo = async () => {
  if (!selectedRecord.value || !selectedRecord.value.id) return
  try {
    const hasOpCode = openAdminKeyDialog();
    if (!hasOpCode) {
      return;
    }
    const opCode = useUserStore().authInfo?.opCode || '';
    // 调用修改基础信息的服务
    // 假设这里有对应的服务方法
    await httpService.modifyApplyRecordBasicInfo({
      recordId: selectedRecord.value.id,
      name: selectedRecord.value.name,
      phone: selectedRecord.value.phone,
      wechat: selectedRecord.value.wechat,
      opCode: opCode
    })

    ElMessage.success('基础信息修改成功')
    basicInfoDialogVisible.value = false
  } catch (error) {
    ElMessage.error('基础信息修改失败')
  }
}

// 确认添加备注
const confirmAddRemark = async () => {
  if (!selectedRecord.value || !selectedRecord.value.id) return
  try {
    const hasOpCode = openAdminKeyDialog();
    if (!hasOpCode) {
      return;
    }
    const opCode = useUserStore().authInfo?.opCode || '';
    // 调用添加备注的服务
    // 假设这里有对应的服务方法
    await httpService.modifyApplyRecordRemark({
      recordId: selectedRecord.value.id,
      remark: newRemark.value,
      opCode: opCode
    })

    selectedRecord.value.remark = newRemark.value
    ElMessage.success('备注添加成功')
    remarkDialogVisible.value = false
  } catch (error) {
    ElMessage.error('备注添加失败')
  }
}

function handleChange(val: boolean) {
  applyRecords.value = []
  fetchRecords()
}

// 获取申请记录
const fetchRecords = async () => {
  loading.value = true
  try {
    const response = await httpService.searchApplyRecords({
      name: findUserName.value,
      phone: findUserMobile.value,
      page: currentPage.value - 1,
      size: pageSize.value,
      status: selectedStatus.value, // 传递筛选条件
    })
    const pageData = response.data
    applyRecords.value = pageData.list
    currentPage.value = pageData.currentPage
    pageSize.value = pageData.pageSize
    total.value = pageData.total
    currentApplyRecords.value = applyRecords.value // 直接赋值给当前页数据
  } finally {
    loading.value = false
  }
}

// 取消申请
const cancelApply = async (id: number) => {
  ElMessageBox.confirm('确认要撤销该申请吗？', '提示', {
    type: 'warning',
  })
    .then(async () => {
      try {
        const hasOpCode = openAdminKeyDialog();
        if (!hasOpCode) {
          return;
        }
        const opCode = useUserStore().authInfo?.opCode || '';
        await httpService.deleteApplyRecord(id, opCode)
        ElMessage.success('撤销成功')
        fetchRecords()
      } catch (error) {
        ElMessage.error('撤销失败，请稍后重试')
      }
    })
    .catch(() => {})
}

// 分页相关方法
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  handleCurrentChange(1)
}

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  fetchRecords() // 直接调用 fetchRecords 方法
}

const handleSortChange = (sort: any) => {
  // 可根据实际需求实现排序逻辑
  console.log('Sort change:', sort)
}

onMounted(() => {
  selectedStatus.value = '' // 明确设置为“全部”选项的值
  fetchRecords()
})
</script>
